// pages/index/h5/controller.js

import { CONTROLLER_URL } from '../../../config';
import { getToken, setToken } from '../../../utils/storage';
import { wxLogin, authUser } from '../../../api/login';

Page({
  /**
   * 页面的初始数据
   */
  data: {
    controllerUrl: '',
    liveid: '',
  },
  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    this.setLiveId(options);

    const isScanEnter = Boolean(options.scene);

    let token = getToken();

    if (!token || isScanEnter) {
      token = await this.loginAndGetToken();
    }

    if (token) {
      this.setControllerUrl(token);
    } else {
      wx.reLaunch({ url: '/pages/index/index' });
    }
  },
  /**
   * 登录并获取token
   * 说明：扫二维码直接进当前页面的情况下需要调用本方法
   */
  async loginAndGetToken() {
    try {
      const { code } = await wxLogin();
      const authInfo = await authUser({ code });
      if (authInfo.token && authInfo.token !== '0') {
        setToken(authInfo.token);
        return authInfo.token;
      } else {
        throw new Error('获取token失败');
      }
    } catch (err) {
      console.log(err);
      wx.showToast({ title: '登录失败', icon: 'none' });
    }
    return null;
  },
  /**
   * 设置遥控器URL
   * @param {*} token
   */
  setControllerUrl(token) {
    this.setData({
      controllerUrl: CONTROLLER_URL + `?liveid=${this.data.liveid}&token=${token}`,
    });
  },
  setLiveId(options) {
    // 二维码进入的场景
    if (options.scene) {
      this.setData({
        liveid: options.scene,
      });
    }
    if (options.liveid) {
      this.setData({
        liveid: options.liveid,
      });
    }
    if (options.splid) {
      this.setData({
        liveid: options.splid,
      });
    }
  },
});
